from django.http import JsonResponse
from rest_framework.response import Response
from logwisdomhub.response import ErrorCode
import logging

logger = logging.getLogger(__name__)

class UnifiedResponseMiddleware:
    """统一响应格式中间件"""
    
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        response = self.get_response(request)
        
        # 只处理API请求
        if request.path.startswith('/api/'):
            # 如果是DRF的Response且没有统一格式，进行转换
            if isinstance(response, Response) and hasattr(response, 'data'):
                if not isinstance(response.data, dict) or 'success' not in response.data:
                    # 转换为统一格式
                    unified_data = {
                        'success': 200 <= response.status_code < 300,
                        'code': ErrorCode.SUCCESS if 200 <= response.status_code < 300 else ErrorCode.GENERAL_ERROR,
                        'data': response.data,
                        'message': '操作成功' if 200 <= response.status_code < 300 else '操作失败'
                    }
                    response.data = unified_data
        
        return response
    
    def process_exception(self, request, exception):
        """处理未捕获的异常"""
        if request.path.startswith('/api/'):
            logger.error(f"API异常: {str(exception)}", exc_info=True)
            return JsonResponse({
                'success': False,
                'code': ErrorCode.UNKNOWN_ERROR,
                'data': None,
                'message': '服务器内部错误'
            }, status=500)
        return None